﻿using System;
using System.Web.Mvc;

namespace Web.Components
{
    public class ShoppingCartModelBinder : IModelBinder
    {
        private const string CartSessionKey = "shoppingcart";
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.Model != null)
            {
                throw new InvalidOperationException("Cannot update instances");
            }

            if (controllerContext.HttpContext.Session != null)
            {
                var cart = controllerContext.HttpContext.Session[CartSessionKey] as ShoppingCart;

                if (cart == null)
                {
                    cart = new ShoppingCart();

                    controllerContext.HttpContext.Session[CartSessionKey] = cart;
                }
                return cart;
            }
            return null;
        }
    }
}